<template>
  <!-- 导航栏 -->
  <van-nav-bar
    title="邮箱验证"
    left-text="返回"
    left-arrow
    @click-left="back"
  />

  <van-form @submit="check">
    <van-field
      v-model="business.email"
      name="email"
      label="邮箱"
      placeholder="请输入邮箱"
      readonly
      :rules="[
        {required: true, message: '请输入邮箱'},
        {pattern:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,message:'邮箱格式不正确'}
      ]"
    />

    <van-field
      v-model="vercode"
      name="vercode"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
      :rules="[
        {required: true, message: '请输入短信验证码'}
      ]"
    >
      <template #button>
        <van-button size="small" type="primary" @click="send" :disabled="disabled">{{msg}}</van-button>
      </template>
    </van-field>

    <div style="width:50%;margin:2em auto;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>

  </van-form>


</template>

<script setup>
  const { proxy } = getCurrentInstance()

  let business = proxy.$cookies.get('business') ? proxy.$cookies.get('business') : {}
  business = reactive(business)

  let vercode = ref('')
  let msg = ref('发送验证码')
  let disabled = ref(false)
  
  //返回上一页
  const back = () => proxy.$router.go(-1)

  // 邮箱验证信息发送
  const send = async () =>
  {
    msg.value = '正在发送中...'
    //倒计时期间不可点击
    disabled.value = true

    //发送接口请求
    var result = await proxy.$POST({
      url:'/business/email',
      params:{
        id:business.id,
        action: 'send'
      }
    })

    //错误信息
    if(result.code == 0)
    {
      proxy.$fail(result.msg)
      return false
    }

    //发送成功
    proxy.$success(result.msg)
    //更改数据 --> 倒计时开始
    msg.value = 60

    // var value = 60
    var T = setInterval(() => {
      if(msg.value <= 0)
      {
        clearInterval(T)
        msg.value = '重新发送验证码'
        //解除不可点击
        disabled.value = false
      }else
      {
        msg.value--
      }
    },100)

  }

  //输入验证码认证
  const check = async (values) => 
  {
    //组装数据
    var data = {
      id: business.id,
      vercode:values.vercode,
      action: 'check',
    }

    //发送请求
    var result = await proxy.$POST({
      url:'/business/email',
      params:data
    })

    if(result == 0)
    {
      proxy.$fail(result.msg)
      return false
    }else
    {
      proxy.$success({
        message:result.msg,
        onClose:() =>
        {
          proxy.$router.go(-1)
        }
      })
    }
  }

</script>